<?php

class Session extends CI_Controller {

 	public function login()
 	{
		//
		// No form post data received
		//
		if (!$this->input->post()) {			
	   		$this->load->helper(array('form'));
            $template_data['title'] = 'Iniciar sesi&oacute;n';
            $template_data['content'] = $this->load->view('session/login', array(), True);
            $this->load->view('templates/main', $template_data);
			return;
		}

		//
		// Post data received
		//

		// Credentials validation
   		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', 'Username',
			'trim|required|xss_clean');
   		$this->form_validation->set_rules(	'password', 'Password',
			'trim|required|xss_clean|callback_authenticate');

   		if($this->form_validation->run() == FALSE)
   		{
     		// Authentication failed!
            $template_data['title'] = 'Inicio de sesi&oacute;n fallido';
            $template_data['content'] = $this->load->view('session/login', array(), True);
            $this->load->view('templates/main', $template_data);
   		}
   		else
   		{
            // Authentication succeed!
            redirect("common/home","refresh");
   		}
 	}
	
	public function authenticate($password)
	{
		$username = $this->input->post('username');
   		$this->load->model('userModel');
		$user = $this->userModel->authenticate($username, $password);
		if ($user)
		{
			$this->_set_session($user);
			return TRUE;
		}
		$this->form_validation->set_message('authenticate', 
			'Nombre de usuario o contraseña inválido');
		return FALSE;
   }

	private function _set_session($user)
	{
		$sess_array = array(
			'dni' => $user->dni,
			'username' => $user->username,
			'group' => $user->group
       	);
       	$this->session->set_userdata('logged_in', $sess_array);
	}
    
    public function logout()
    {
        $this->session->unset_userdata('id');
        $this->session->unset_userdata('username');
        $this->session->unset_userdata('group');
        $this->session->sess_destroy();
        redirect('session/login', 'refresh');
    }
}

?>
